package com.lyj.validates.exceptions;

import com.lyj.validates.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 全局异常处理
 * @author: zhanglei
 * @version: 1.0
 * @date: 2021/5/18 20:27
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 校验异常
     * @author: liyajie
     * @date: 2022/1/20 13:07
     * @param e
     * @return com.lyj.validates.common.R
     * @exception:
     * @update:
     * @updatePerson:
     **/
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public R exceptionHandler(MethodArgumentNotValidException e) {
        log.error("exceptionHandler info:", e);
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder builder = new StringBuilder();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            builder.append(fieldError.getDefaultMessage()).append("!");
        }
        log.error("message : {}",builder.toString());
        return new R("500",builder.toString());
    }



    /**
     * 处理其他异常
     * @param e 异常
     * @return RetResult
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R exceptionHandler(Exception e) {
        log.error("异常:", e);
        return new R("500", e.getMessage());
    }

}
